package org.jeecg.modules.system.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.UserOrgVo;
import org.jeecg.common.util.ListUtils;
import org.jeecg.common.util.UUIDGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.scm.api.ScmCusInfoAPI;
import org.jeecg.modules.system.entity.SysOrganization;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysOrganizationService;
import org.jeecg.modules.system.service.ISysUserService;
import org.jeecg.modules.system.vo.SysOrganizationVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @Description: sys_organization
 * @Author: jeecg-boot
 * @Date: 2021-10-29
 * @Version: V1.0
 */
@Api(tags = "机构管理")
@RestController
@RequestMapping("/sys/organization")
@Slf4j
public class SysOrganizationController extends JeecgController<SysOrganization, ISysOrganizationService> {
    @Autowired
    private ISysOrganizationService sysOrganizationService;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private ScmCusInfoAPI cusInfoAPI;


    @ApiOperation(value = "根据机构ID查找上级机构", notes = "根据机构ID查找上级机构")
    @RequestMapping(value = "/queryParentIdsById", method = RequestMethod.GET)
    public Result<Map<String, List<String>>> queryParentIdsById(String organizationId) {
        SysOrganization sysOrganization = sysOrganizationService.getById(organizationId);
        Result<Map<String, List<String>>> result = new Result<>();
        if (oConvertUtils.isEmpty(sysOrganization)) {
            result.error500("不存在此机构");
            return result;
        }
        Map<String, List<String>> map = new HashMap<>();
        List<String> parentIds = new ArrayList<>();
        sysOrganizationService.queryParentIdsById(parentIds, organizationId);
        if (oConvertUtils.listIsEmpty(parentIds)) {
            result.setMessage("未找到上级机构信息");
        }
        map.put(organizationId, parentIds);
        result.setResult(map);
        result.setCode(CommonConstant.SC_OK_200);
        result.setSuccess(true);
        return result;
    }


    @ApiOperation(value = "根据用户ID查找用户所属机构", notes = "根据用户ID查找用户所属机构")
    @RequestMapping(value = "/queryByUserId", method = RequestMethod.GET)
    public Result<SysOrganization> queryByUserId(String userId) {
        Result<SysOrganization> result = sysOrganizationService.queryByUserId(userId);
        return result;
    }

    @ApiOperation(value = "查找用户机构或上级机构", notes = "根据用户ID查找")
    @GetMapping(value = "/queryOrgs")
    public UserOrgVo queryOrgs(@RequestParam String userId, @RequestParam Boolean needParents) {
        UserOrgVo userOrgVo = sysOrganizationService.queryOrgs(userId, needParents);
        return userOrgVo;
    }

    @ApiOperation(value = "查询所有机构", notes = "查询所有机构")
    @RequestMapping(value = "/queryAll", method = RequestMethod.GET)
    public Result<List<SysOrganizationVO>> queryAll() {
        Result<List<SysOrganizationVO>> result = new Result<>();
        LambdaQueryWrapper<SysOrganization> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.isNull(SysOrganization::getParentId).or().eq(SysOrganization::getParentId, "");
        List<SysOrganization> list = sysOrganizationService.list(queryWrapper);
        if (list == null || list.size() <= 0) {
            result.error500("未找到机构信息");
        } else {
            ListUtils<SysOrganizationVO> utils = BeanUtils.instantiate(ListUtils.class);
            List<SysOrganizationVO> sysOrganizationVOList = new ArrayList<>();
            utils.copyList(list, sysOrganizationVOList, SysOrganizationVO.class);
            for (SysOrganizationVO sysOrganizationVO : sysOrganizationVOList) {
                sysOrganizationService.queryChildren(sysOrganizationVO);
            }
            result.setCode(CommonConstant.SC_OK_200);
            result.setResult(sysOrganizationVOList);
            result.setSuccess(true);
        }
        return result;
    }


    @ApiOperation(value = "通过ID查询机构及其所有子机构", notes = "通过ID查询机构及其所有子机构")
    @RequestMapping(value = "/queryChildren", method = RequestMethod.GET)
    public Result<SysOrganizationVO> queryChild(String id) {
        Result<SysOrganizationVO> result = new Result<>();
        SysOrganization sysOrganization = sysOrganizationService.getById(id);
        if (oConvertUtils.isEmpty(sysOrganization)) {
            result.error500("未找到机构信息");
        } else {
            SysOrganizationVO sysOrganizationVO = new SysOrganizationVO();
            BeanUtils.copyProperties(sysOrganization, sysOrganizationVO);
            sysOrganizationService.queryChildren(sysOrganizationVO);
            result.setCode(CommonConstant.SC_OK_200);
            result.setResult(sysOrganizationVO);
            result.setSuccess(true);
        }
        return result;
    }

    /**
     * 分页列表查询
     *
     * @param sysOrganization
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "机构分页列表查询")
    @ApiOperation(value = "机构分页列表查询", notes = "机构分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(SysOrganization sysOrganization,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<SysOrganization> queryWrapper = QueryGenerator.initQueryWrapper(sysOrganization, req.getParameterMap());
        Page<SysOrganization> page = new Page<SysOrganization>(pageNo, pageSize);
        IPage<SysOrganization> pageList = sysOrganizationService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param sysOrganization
     * @return
     */
    @AutoLog(value = "添加机构")
    @ApiOperation(value = "添加机构", notes = "添加机构")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody SysOrganization sysOrganization) {
        Result<?> scmCusInfo = cusInfoAPI.queryByField("cus_no", sysOrganization.getCustomerId().toString());
        //查询是否有此客户
        if (oConvertUtils.isEmpty(scmCusInfo.getResult())) {
            return Result.error("没有此客户");
        }
        sysOrganization.setOrganizationId(UUIDGenerator.generate());
        sysOrganizationService.save(sysOrganization);
        return Result.OK("添加成功！");
    }


    /**
     * 编辑
     *
     * @param sysOrganization
     * @return
     */
    @AutoLog(value = "编辑机构")
    @ApiOperation(value = "编辑机构", notes = "编辑机构")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody SysOrganization sysOrganization) {
        Result<?> scmCusInfo = cusInfoAPI.queryByField("cus_no", sysOrganization.getCustomerId().toString());
        if (oConvertUtils.isEmpty(scmCusInfo.getResult())) {
            return Result.error("没有此客户");
        }
        sysOrganizationService.updateById(sysOrganization);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "通过id删除机构")
    @ApiOperation(value = "通过id删除机构", notes = "通过id删除机构")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        LambdaQueryWrapper<SysUser> userQueryWrapper = new LambdaQueryWrapper<>();
        userQueryWrapper.eq(SysUser::getOrganizationId, id);
        List<SysUser> userList = sysUserService.list(userQueryWrapper);
        if (oConvertUtils.listIsNotEmpty(userList)) {
            return Result.error("该机构存在用户，请先删除用户！");
        }

        LambdaQueryWrapper<SysOrganization> orgQueryWrapper = new LambdaQueryWrapper<>();
        orgQueryWrapper.eq(SysOrganization::getParentId, id);
        List<SysOrganization> orgList = sysOrganizationService.list(orgQueryWrapper);
        if (oConvertUtils.listIsNotEmpty(orgList)) {
            return Result.error("该机构存在子机构，请先删除子机构！");
        }
        sysOrganizationService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "批量删除机构")
    @ApiOperation(value = "批量删除机构", notes = "批量删除多个id用,分隔")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        String msg = "";
        List<String> idsList = Arrays.asList(ids.split(","));
        for (String id : idsList) {
            LambdaQueryWrapper<SysUser> userQueryWrapper = new LambdaQueryWrapper<>();
            userQueryWrapper.eq(SysUser::getOrganizationId, id);
            List<SysUser> userList = sysUserService.list(userQueryWrapper);
            if (oConvertUtils.listIsNotEmpty(userList)) {
                return Result.error("该机构存在用户，请先删除用户！");
            }
            LambdaQueryWrapper<SysOrganization> orgQueryWrapper = new LambdaQueryWrapper<>();
            orgQueryWrapper.eq(SysOrganization::getParentId, id);
            List<SysOrganization> list = sysOrganizationService.list(orgQueryWrapper);
            if (oConvertUtils.listIsEmpty(list)) {
                SysOrganization sysOrganization = sysOrganizationService.getById(id);
                msg = msg + sysOrganization.getName() + " ";
            }
        }
        if (!msg.equals("")) {
            return Result.error(msg + "存在子机构，请先删除子机构");
        }
        this.sysOrganizationService.removeByIds(idsList);
        return Result.OK("批量删除成功!");
    }

    /**
     * 模糊查询
     *
     * @param sysOrganization
     * @return
     */
    @AutoLog(value = "模糊查询机构")
    @ApiOperation(value = "模糊查询机构", notes = "根据name、nickname、description字段模糊查询机构")
    @GetMapping(value = "/fuzzyQuery")
    public Result<?> fuzzyQuery(@RequestBody SysOrganization sysOrganization) {
        QueryWrapper<SysOrganization> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("1", "1");
        if (!oConvertUtils.isEmpty(sysOrganization.getName())) {
            queryWrapper.like("name", sysOrganization.getName());
        }
        if (!oConvertUtils.isEmpty(sysOrganization.getNickname())) {
            queryWrapper.like("nickname", sysOrganization.getNickname());
        }
        if (!oConvertUtils.isEmpty(sysOrganization.getDescription())) {
            queryWrapper.like("description", sysOrganization.getDescription());
        }
        List<SysOrganization> organizationList = sysOrganizationService.list(queryWrapper);
        return Result.OK(organizationList);
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "通过id查询机构")
    @ApiOperation(value = "通过id查询机构", notes = "通过id查询机构")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        SysOrganization sysOrganization = sysOrganizationService.getById(id);
        if (sysOrganization == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(sysOrganization);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param sysOrganization
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, SysOrganization sysOrganization) {
        return super.exportXls(request, sysOrganization, SysOrganization.class, "sys_organization");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, SysOrganization.class);
    }

}
